package com.guoju.tyframework.mvc.context;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;

import org.jdom.JDOMException;

import com.guoju.tyframework.mvc.config.BeanProperty;
import com.guoju.tyframework.mvc.config.MvcBeans;
import com.guoju.tyframework.mvc.providers.ActionXmlProvider;
import com.guoju.tyframework.mvc.utils.CommonUtils;
import com.guoju.tyframework.mvc.utils.TypeEnum;

public class FullActionParams {
	
	public FullActionParams(){}

	/**
	 * 递归加载action中的属性值 根据前台传参
	 * @param t 由代理创建的action类
	 * @param beanClass
	 * @param actionClassName
	 * @param req
	 * @return
	 */
	//TODO 有待改造
	public static <T> T ioc(T t,MvcBeans bean,HttpServletRequest req){
		try {
			Class clazz= Class.forName(bean.getBeanClass());
			t=(T)clazz.newInstance();
			t=recursion(clazz, t, bean, req);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println(e.getMessage());
		}
		System.out.println("----后台接收params结果如下----\r\n"+t.toString());
		return t;
	}
	public static <T> T recursion(Class clazz,T t,MvcBeans bean,HttpServletRequest req) 
			throws ClassNotFoundException, NoSuchMethodException, 
			SecurityException, JDOMException, IOException, InstantiationException, IllegalAccessException, 
			IllegalArgumentException, InvocationTargetException, ParseException{
		LinkedList<BeanProperty> properties=bean.getProperties();
		for (BeanProperty property : properties) {
			String type=property.getType();
			type=TypeEnum.getPackageTypeByMeta(type);//将简写的type转换成带路径的
			String fieldName=property.getName();
			Class fieldType=Class.forName(type);
			Method m=clazz.getMethod("set"+CommonUtils.toUpperCaseFirstOne(fieldName),fieldType);
			//如果不是基础类型
			if(!TypeEnum.contains(type)){
				String id=property.getRef();
				MvcBeans subBean=ActionXmlProvider.getBeansByid(id, req);
				Object obj=fieldType.newInstance();
			/*	System.out.println("-----");
				System.out.println(obj.getClass());
				System.out.println("-----");*/
				obj=recursion(fieldType, obj, subBean, req);
				m.invoke(t, obj);
			}else{
				String strValue= req.getParameter(fieldName);
				//TODO 不一定所有的都是String类型[数组类型怎么处理]
				if(!CommonUtils.isEmpty(strValue)){
					if(TypeEnum.enum1.getPackageType().equals(type)){
						m.invoke(t,strValue);
					}else if(TypeEnum.enum2.getPackageType().equals(type)){
						m.invoke(t,Integer.parseInt(strValue));
					}else if(TypeEnum.enum3.getPackageType().equals(type)){
						m.invoke(t,CommonUtils.parseStrByPattern(strValue,"yyyy-MM-dd"));
					}else if(TypeEnum.enum4.getPackageType().equals(type)){
						m.invoke(t,Double.parseDouble(strValue));
					}else{
						System.err.println("------数据类型暂不识别-----");
					}
					
				}
			}
		}
			return t;
	}
	

}
